import * as echarts from 'echarts';
import {LitElement, html, TemplateResult} from 'lit';
import {customElement, property} from "lit/decorators.js";
import style from '../echarts.css.ts';

export interface BarYStackProps {
    chartId?: string;
    width?: string;
    height?: string;
    legend?: string[];
    grid?: object;
    yAxisData?: string[];
    seriesData?: number[][];
}

@customElement('lit-bar-y-stack')
export class LitBarYStack extends LitElement {
    @property({type: String}) chartId: string = 'lit-bar-y-stack-chart';
    @property({type: String}) width: string = '600px';
    @property({type: String}) height: string = '400px';
    @property({type: Object}) legend: string[] = ['Direct', 'Mail Ad', 'Affiliate Ad', 'Video Ad', 'Search Engine'];
    @property({type: Object}) grid: any = {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    };
    @property({type: Array}) yAxisData: string[] = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    @property({type: Array}) seriesData: number[][] = [
        [320, 302, 301, 334, 390, 330, 320],
        [120, 132, 101, 134, 90, 230, 210],
        [220, 182, 191, 234, 290, 330, 310],
        [150, 212, 201, 154, 190, 330, 410],
        [820, 832, 901, 934, 1290, 1330, 1320]
    ];

    getSeries(): any[] {
        return this.seriesData.map((data, index) => ({
            name: this.legend[index] || undefined,
            type: 'bar',
            stack: 'total',
            label: {
                show: true
            },
            emphasis: {
                focus: 'series'
            },
            data: data
        }));
    }

    option: echarts.EChartsOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
            }
        },
        legend: {data: this.legend},
        grid: this.grid,
        xAxis: {
            type: 'value'
        },
        yAxis: {
            type: 'category',
            data: this.yAxisData,
        },
        series: this.getSeries(),
    };

    static styles = style;

    updated() {
        this.option.legend = {data: this.legend};
        this.option.grid = this.grid;
        (this.option.yAxis as any).data = this.yAxisData;
        this.option.series = this.getSeries();
        this.firstUpdated();
    }

    firstUpdated() {
        const chart = echarts.init(this.shadowRoot!.getElementById(this.chartId)!);
        chart.setOption(this.option);
    }

    render(): TemplateResult {
        return html`<div id="${this.chartId}" style="width:${this.width};height:${this.height};"></div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'lit-bar-y-stack': LitBarYStack;
    }
}